package com.crm.system.controller.csd.customerManager;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.DateUtil;
import com.crm.common.util.ExcelUtil4;
import com.crm.model.qo.csd.customerManager.CustomerInfoQO;
import com.crm.model.vo.csd.customerManager.CustomerInfoVO;
import com.crm.model.vo.csd.customerManager.ImportCustomerInfoVO;
import com.crm.system.service.cluePoolManager.ExcelUtil;
import com.crm.system.service.csd.customerManager.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangpeng
 * 客户管理---客户信息库列表
 * @Date 2021/9/27 10:51
 */
@RestController
@RequestMapping("/csd/customerInfo")
@Slf4j
public class CustomerInfoController {

    @Autowired
    private CustomerService customerService;

    /**
     * selectCustomerInfoList
     * 客户信息库列表
     * @Author wangpeng
     * @Date 2021/9/27
     * @param pageIndex	
     * @param pageSize	
     * @param sortName	
     * @param sortOrder	
     * @param customerQO	
     * @return
     */
    @PostMapping("/selectCustomerInfoList")
    public DataResponse selectCustomerInfoList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                               @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                               @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                               @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                               CustomerInfoQO customerQO//查询条件
    ){
        try{
            DhPageInfo<CustomerInfoVO> customerVOList = customerService.selectCustomerInfoList(customerQO,pageIndex,pageSize,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerVOList);
        }catch(Exception e){
            log.error("CustomerInfoController selectCustomerInfoList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * uploadExcel
     * 客户信息库导入
     * @Author wangpeng
     * @Date 2021/10/12
     * @param file
     * @return
     */
    @PostMapping("/uploadExcel")
    public DataResponse uploadExcel(@RequestParam MultipartFile file)throws Exception{
        JSONObject jsonObject = new JSONObject();
        String fileName = file.getOriginalFilename();
        String xls = "xls";
        String xlsx = "xlsx";
        if (!fileName.endsWith(xls) || !fileName.endsWith(xlsx)) {

        } else {
            jsonObject.put("code", 1);
            jsonObject.put("msg", "文件不是Excel文件");
        }
        try {
            ExcelUtil excelUtil = new ExcelUtil();
            List<ImportCustomerInfoVO> list = excelUtil.excelImport(file.getInputStream(), ImportCustomerInfoVO.class);//1.读取前端的excel文件并转换成list集合
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }
            jsonObject = customerService.uploadExcel(list);

        } catch (Exception e) {
            log.error("returnMoney importBackMoney:", e);
        }

        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), jsonObject);

    }


    /**
     * exportExcel
     * 客户信息库导出
     * @Author renshaorong
     * @Date 2021/11/30
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value="/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("客户信息库导出 "+ DateUtil.getDate("yyyy-MM-dd HH:mm:ss"), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = ExcelUtil4.getHorizontalCellStyleStrategy();
            List<ImportCustomerInfoVO> list = customerService.exportExcel();
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), ImportCustomerInfoVO.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("Sheet1")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }


    /**
     * 新增
     * @return
     */
    @PostMapping("/addCustomerInfo")
    public DataResponse addCustomerInfo(@RequestBody CustomerInfoQO customerInfoQO){
        boolean b = customerService.addCustomerInfo(customerInfoQO);
        if (b){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 查询客户信息库的省份信息
     * selectProviceList
     * @Author wangpeng
     * @Date 2021/12/2
     * @param
     * @return
     */
    @PostMapping("/selectProviceList")
    public DataResponse selectProviceList(){
        try {
            List<CustomerInfoVO> vo = customerService.selectProviceList();
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),vo);
        }catch (Exception e){
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 根据省份信息查询客户信息库的城市信息
     * selectCityByProvice
     * @Author wangpeng
     * @Date 2021/12/2
     * @param provice
     * @return
     */
    @PostMapping("/selectCityByProvice")
    public DataResponse selectCityByProvice(String provice){
        try {
            List<CustomerInfoVO> vo = customerService.selectCityByProvice(provice);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),vo);
        }catch (Exception e){
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 根据省份、城市信息查询客户信息库的县区信息
     * selectDistrictByProviceCity
     * @Author wangpeng
     * @Date 2021/12/2
     * @param provice
     * @param city
     * @return
     */
    @PostMapping("/selectDistrictByProviceCity")
    public DataResponse selectDistrictByProviceCity(String provice,String city){
        try {
            List<CustomerInfoVO> vo = customerService.selectDistrictByProviceCity(provice,city);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),vo);
        }catch (Exception e){
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 查询未删除的所有行业
     * selectIndustryTypeList
     * @Author wangpeng
     * @Date 2021/12/2
     * @param
     * @return
     */
    @PostMapping("/selectIndustryTypeList")
    public DataResponse selectIndustryTypeList(){
        try {
            List<CustomerInfoVO> vo = customerService.selectIndustryTypeList();
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),vo);
        }catch (Exception e){
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     *【客服部】客户信息库列表-详细-调整
     * @author yincuimei
     * @return
     */
    @PostMapping("/updateCompanyAndAccountById")
    public DataResponse updateCompanyAndAccountById(@RequestParam(value="customerInfoId") String customerInfoId,//主键
                                                    @RequestParam(value="companyId",required = false) String companyId,//所属公司ID
                                                    @RequestParam(value="accountId",required = false) String accountId//所有人ID
                                                    ){
        Boolean result = customerService.updateCompanyAndAccountById(customerInfoId,companyId,accountId);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
    }
}
